package com.htu.courseService.auth.strategy;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.htu.courseService.auth.vo.LoginRequest;
import com.htu.courseService.auth.vo.LoginResponse;
import com.htu.courseService.common.enums.RedisCachePrefix;
import com.htu.courseService.common.enums.ResponseCodeEnum;
import com.htu.courseService.common.exception.BaseException;
import com.htu.courseService.common.util.RedisCache;
import com.htu.courseService.common.util.SymmetricCryptoUtil;
import com.htu.courseService.user.dao.UserMapper;
import com.htu.courseService.user.dao.UserRoleMapper;
import com.htu.courseService.user.entity.User;
import com.htu.courseService.user.vo.UserInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created By JNNarrator on 2024/9/7 16:43
 * email: jiangn09@chinatelecom.cn
 */
@Component("pwd")
@RequiredArgsConstructor
public class PwdLoginStrategy implements LoginStrategy, RedisCachePrefix {
	private final RedisCache redisCache;

	private  final UserMapper userMapper;

	private  final UserRoleMapper userRoleMapper;
	@Override
	public LoginResponse login(LoginRequest request) {
		String username = request.getUsername();
		String password = request.getPassword();
		//UserInfo userInfo = redisCache.getCacheObject(USER_INFO + username, UserInfo.class);
		LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(User::getUsername,username);
		User user = userMapper.selectOne(wrapper);
		if (Objects.isNull(user)){
			throw new BaseException(ResponseCodeEnum.USER_NOT_FOUND);
		}
		UserInfo userInfo = BeanUtil.copyProperties(user, UserInfo.class,"password");
		getPer(userInfo);
		String passwordEncode = SymmetricCryptoUtil.encode(password);
		if (!Objects.equals(passwordEncode,user.getPassword())){
			throw new BaseException(ResponseCodeEnum.PASSWORD_ERROR);
		}
		return this.loginSuccess(userInfo);
	}
	
	public void getPer(UserInfo userInfo){
		List<Map<String, String>> userPermissionInfo = userMapper.getUserPermissionInfo(userInfo.getUsername());
		Map<String, List<String>> collect = userPermissionInfo.stream()
				.collect(
						Collectors.groupingBy(stringStringMap -> stringStringMap.get("role_code"),
								Collectors.mapping(stringStringMap -> stringStringMap.get("permission_code"), Collectors.toList()))
				);
		userInfo.setRolesAndPermissions(collect);
	}
}
